<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :inline="true" class="search-form">
      <el-form-item label="登录账户">
        <el-input v-model="searchForm.loginName" placeholder="请输入登录账户" clearable />
      </el-form-item>
      <el-form-item label="用户名">
        <el-input v-model="searchForm.userName" placeholder="请输入用户名" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="operation-btns">
      <el-button type="primary" @click="handleCreate">
        <el-icon><Plus /></el-icon>
        新增用户
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
        :data="userList"
        :header-cell-style="{'text-align':'center'}"
        :cell-style="{'text-align':'center'}"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
    >

      <el-table-column prop="icon" label="头像" >
        <template #default="scope">
          <el-avatar :size="50" :src="scope.row.icon" />
        </template>
      </el-table-column>
      <el-table-column prop="loginName" label="账户" />
      <el-table-column prop="userName" label="昵称" />
<!--      <el-table-column prop="phone" label="手机号"  />-->
      <el-table-column prop="email" label="邮箱" />
      <el-table-column label="用户类型">
        <template #default="{ row }">
          <el-tag :type="row.userType === 'admin' ? 'danger' : 'success'">
            {{ row.userType === 'admin' ? '超级管理员' : '普通用户' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" fixed = "right">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        background
        v-model:current-page="pagination.pageNo"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        layout="jumper, prev, pager, next,sizes, total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'create' ? '新增用户' : '编辑用户'"
        width="600px"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="登录账户" prop="loginName">
          <el-input v-model="formData.loginName" />
        </el-form-item>

        <el-form-item label="登录密码" prop="loginPassword" v-if="dialogType === 'create'">
          <el-input
              v-model="formData.loginPassword"
              type="password"
              show-password
              placeholder="6-20位字符"
          />
        </el-form-item>

        <el-form-item label="用户名" prop="userName">
          <el-input v-model="formData.userName" />
        </el-form-item>

        <el-form-item label="用户类型" prop="userType">
          <el-select v-model="formData.userType">
            <el-option label="普通用户" value="user" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>

        <el-form-item label="手机号">
          <el-input v-model="formData.phone" />
        </el-form-item>

        <el-form-item label="邮箱">
          <el-input v-model="formData.email" type="email" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from '@/utils/request'

// 搜索表单数据
const searchForm = reactive({
  loginName: '',
  userName: '',
  phone: ''
})

// 分页数据
const pagination = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const userList = ref([])
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('create')
const formRef = ref()
const formData = reactive({
  id: null,
  loginName: '',
  loginPassword: '',
  userName: '',
  userType: 'user',
  phone: '',
  email: ''
})

// 表单验证规则
const formRules = reactive({
  loginName: [
    { required: true, message: '请输入登录账户', trigger: 'blur' },
    { min: 3, max: 20, message: '长度3-20个字符', trigger: 'blur' }
  ],
  loginPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度6-20个字符', trigger: 'blur' }
  ],
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  userType: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ]
})

// 初始化加载数据
const fetchUserList = async () => {
  try {
    loading.value = true
    const params = {
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      ...searchForm
    }

    const response = (await axios.post('/users/listUser', params)).data

    if (response.success) {
      // 修正数据字段路径
      userList.value = response.data || []
      // 修正总数字段
      pagination.total = response.total || 0
    } else {
      ElMessage.error(response.message || '获取数据失败')
    }
  } catch (error) {
    // 增强错误信息
    console.error('请求错误详情:', error)
    ElMessage.error(`请求失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageNo = 1
  fetchUserList()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    loginName: '',
    userName: '',
    phone: ''
  })
  handleSearch()
}

// 分页变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchUserList()
}

const handlePageChange = (page) => {
  pagination.pageNo = page
  fetchUserList()
}

// 打开新增对话框
const handleCreate = () => {
  dialogType.value = 'create'
  resetForm()
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(formData, {
    id: row.id,
    loginName: row.loginName,
    userName: row.userName,
    userType: row.userType,
    phone: row.phone,
    email: row.email
  })
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    const response = (await axios.post('/users/saveOrUpdateUser', formData)).data
    if (response.success) {
      ElMessage.success(response.message || '操作成功')
      dialogVisible.value = false
      fetchUserList()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    ElMessage.error('表单提交失败')
  }
}

// 删除用户
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确认删除该用户？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = (await axios.post(`/users/deleteUser`, {"id": id})).data
    if (response.success) {
      ElMessage.success('删除成功')
      fetchUserList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    // 用户取消删除
  }
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(formData, {
    id: null,
    loginName: '',
    loginPassword: '',
    userName: '',
    userType: 'user',
    phone: '',
    email: ''
  })
}

// 初始化加载
onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-form {
  background: #f8f8f8;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.operation-btns {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.el-table {
  margin-top: 15px;
}
</style>